// 生活记录应用的JavaScript代码

// 定义记录的数据结构
class Entry {
    constructor(id, title, content, date, mood) {
        this.id = id;
        this.title = title;
        this.content = content;
        this.date = date;
        this.mood = mood;
    }
}

// 初始化页面
function init() {
    // 设置默认日期为今天
    document.getElementById('date').valueAsDate = new Date();
    
    // 绑定表单提交事件
    document.getElementById('entryForm').addEventListener('submit', handleFormSubmit);
    
    // 绑定搜索和筛选事件
    document.getElementById('searchInput').addEventListener('input', filterEntries);
    document.getElementById('filterMood').addEventListener('change', filterEntries);
    
    // 加载并显示记录
    loadEntries();
}

// 处理表单提交
function handleFormSubmit(e) {
    e.preventDefault();
    
    const title = document.getElementById('title').value;
    const content = document.getElementById('content').value;
    const date = document.getElementById('date').value;
    const mood = document.getElementById('mood').value;
    
    // 生成唯一ID
    const id = Date.now().toString();
    
    // 创建新记录
    const newEntry = new Entry(id, title, content, date, mood);
    
    // 保存到localStorage
    saveEntry(newEntry);
    
    // 重置表单
    document.getElementById('entryForm').reset();
    document.getElementById('date').valueAsDate = new Date();
    
    // 重新加载记录列表
    loadEntries();
    
    // 显示成功提示
    showNotification('记录保存成功！');
}

// 保存记录到localStorage
function saveEntry(entry) {
    // 获取现有记录
    const entries = getEntries();
    
    // 添加新记录
    entries.push(entry);
    
    // 保存回localStorage
    localStorage.setItem('lifeEntries', JSON.stringify(entries));
}

// 从localStorage获取所有记录
function getEntries() {
    const entriesJson = localStorage.getItem('lifeEntries');
    return entriesJson ? JSON.parse(entriesJson) : [];
}

// 加载并显示记录
function loadEntries() {
    const entries = getEntries();
    const entriesList = document.getElementById('entriesList');
    
    // 清空现有列表
    entriesList.innerHTML = '';
    
    // 如果没有记录，显示空状态
    if (entries.length === 0) {
        entriesList.innerHTML = `
            <div class="empty-state">
                <h3>还没有记录</h3>
                <p>开始记录你的生活点滴吧！</p>
            </div>
        `;
        return;
    }
    
    // 按日期降序排序（最新的在前）
    entries.sort((a, b) => new Date(b.date) - new Date(a.date));
    
    // 创建记录卡片
    entries.forEach(entry => {
        const card = createEntryCard(entry);
        entriesList.appendChild(card);
    });
}

// 创建记录卡片元素
function createEntryCard(entry) {
    const card = document.createElement('div');
    card.className = 'entry-card';
    
    // 格式化日期显示
    const formattedDate = new Date(entry.date).toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric'
    });
    
    card.innerHTML = `
        <h3>${escapeHtml(entry.title)}</h3>
        <p class="date">${formattedDate}</p>
        <span class="mood ${entry.mood}">${getMoodText(entry.mood)}</span>
        <p class="content">${escapeHtml(entry.content)}</p>
        <div class="actions">
            <button class="btn btn-secondary" onclick="editEntry('${entry.id}')">编辑</button>
            <button class="btn btn-danger" onclick="deleteEntry('${entry.id}')">删除</button>
        </div>
    `;
    
    return card;
}

// 获取心情文本
function getMoodText(mood) {
    const moodMap = {
        happy: '开心',
        excited: '兴奋',
        calm: '平静',
        sad: '难过',
        tired: '疲惫'
    };
    return moodMap[mood] || mood;
}

// 转义HTML特殊字符
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// 过滤记录
function filterEntries() {
    const searchTerm = document.getElementById('searchInput').value.toLowerCase();
    const moodFilter = document.getElementById('filterMood').value;
    
    const entries = getEntries();
    const entriesList = document.getElementById('entriesList');
    
    // 清空列表
    entriesList.innerHTML = '';
    
    // 过滤记录
    const filteredEntries = entries.filter(entry => {
        const matchesSearch = entry.title.toLowerCase().includes(searchTerm) || 
                             entry.content.toLowerCase().includes(searchTerm);
        const matchesMood = !moodFilter || entry.mood === moodFilter;
        return matchesSearch && matchesMood;
    });
    
    // 按日期排序
    filteredEntries.sort((a, b) => new Date(b.date) - new Date(a.date));
    
    // 显示过滤后的记录
    if (filteredEntries.length === 0) {
        entriesList.innerHTML = `
            <div class="empty-state">
                <h3>没有找到匹配的记录</h3>
                <p>试试其他搜索条件吧</p>
            </div>
        `;
        return;
    }
    
    filteredEntries.forEach(entry => {
        const card = createEntryCard(entry);
        entriesList.appendChild(card);
    });
}

// 编辑记录
function editEntry(id) {
    const entries = getEntries();
    const entry = entries.find(e => e.id === id);
    
    if (entry) {
        // 填充表单
        document.getElementById('title').value = entry.title;
        document.getElementById('content').value = entry.content;
        document.getElementById('date').value = entry.date;
        document.getElementById('mood').value = entry.mood;
        
        // 删除原记录
        deleteEntryFromStorage(id);
        
        // 滚动到表单
        document.querySelector('.add-entry').scrollIntoView({ behavior: 'smooth' });
    }
}

// 删除记录
function deleteEntry(id) {
    if (confirm('确定要删除这条记录吗？')) {
        deleteEntryFromStorage(id);
        loadEntries();
        showNotification('记录已删除');
    }
}

// 从存储中删除记录
function deleteEntryFromStorage(id) {
    const entries = getEntries();
    const updatedEntries = entries.filter(entry => entry.id !== id);
    localStorage.setItem('lifeEntries', JSON.stringify(updatedEntries));
}

// 显示通知
function showNotification(message) {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = 'notification';
    notification.textContent = message;
    
    // 添加样式
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background-color: #4CAF50;
        color: white;
        padding: 15px 20px;
        border-radius: 5px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.2);
        z-index: 1000;
        animation: slideIn 0.3s ease-out;
    `;
    
    // 添加动画
    const style = document.createElement('style');
    style.textContent = `
        @keyframes slideIn {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }
    `;
    document.head.appendChild(style);
    
    // 添加到文档
    document.body.appendChild(notification);
    
    // 3秒后移除
    setTimeout(() => {
        notification.style.opacity = '0';
        notification.style.transform = 'translateX(100%)';
        notification.style.transition = 'opacity 0.3s, transform 0.3s';
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 3000);
}

// 页面加载完成后初始化
window.addEventListener('DOMContentLoaded', init);